<template>
  <div>
      <el-card class="box-card">
        <el-page-header @back="goBack" :content="article_id === 0 ? '新增新闻' : '编辑新闻'"></el-page-header>
      </el-card>
      <div>
        <el-card class="ivu-mt">
          <el-form :model="addForm" :rules="addRules" ref="AddRefForm" label-width="90px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="文章名称" prop="title">
                  <el-input v-model="addForm.title"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="类别">
                  <el-select v-model="addForm.column_id" placeholder="请选择文章类别" style="width: 100%">
                    <el-option v-for="(item,index) in articleTypeList" :key="index" :label="item" :value="index"></el-option>
                  </el-select>
                </el-form-item>
<!--                <el-form-item label="文章副名称">-->
<!--                  <el-input v-model="addForm.sub_title"></el-input>-->
<!--                </el-form-item>-->
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="关键字">
                  <el-input v-model="addForm.keyword"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="文章描述">
                  <el-input v-model="addForm.description"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="来源">
                  <el-input v-model="addForm.source"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="作者">
                  <el-input v-model="addForm.author"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="热门">
                  <el-switch
                    v-model="addForm.hot">
                  </el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="置顶">
                  <el-switch
                    v-model="addForm.top">
                  </el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="状态">
                  <el-switch
                    v-model="addForm.status">
                  </el-switch>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="封面图" prop="img" ref="image">
              <el-upload
                :action="upload.url"
                :headers="upload.headers"
                :accept="upload.accept"
                list-type="picture-card"
                :data="upload.data"
                :limit="upload.limitCount"
                :file-list="pathList"
                :on-remove="handleRemove"
                :on-exceed="onExceed"
                :on-success="onSuccess"
                :on-preview="handlePictureCardPreview">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-upload
                style="display: none"
                class="quill-avatar-uploader"
                :action="upload.url"
                :headers="upload.headers"
                :accept="upload.accept"
                :data="upload.data"
                :show-file-list="false"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :before-upload="beforeUpload"></el-upload>
            <el-form-item label="内容">
              <el-row v-loading="quillUpdateImg">
               <quill-editor ref="myQuillEditor" v-model="addForm.content"  class="ql-editor-class" :options="editorOption"></quill-editor>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveArticle">{{article_id === 0 ? '立即创建' : '立即更新'}}</el-button>
              <el-button>取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </div>

  </div>
</template>

<script>
const toolbarOptions = [
  // toggled buttons
  ['bold', 'italic', 'underline', 'strike'],
  ['blockquote'],
  // custom button values
  [{'header': 1}, {'header': 2}],
  [{'list': 'ordered'}, {'list': 'bullet'}],
  // superscript/subscript
  [{'script': 'sub'}, {'script': 'super'}],
  // outdent/indent
  [{'indent': '-1'}, {'indent': '+1'}],
  // text direction
  [{'direction': 'rtl'}],
  [{'size': ['10px', '12px', '14px', '16px', '18px', '20px', '22px', '24px', '26px', '32px', '48px']}],
  // custom dropdown
  [{'header': [1, 2, 3, 4, 5, 6, false]}],
  // dropdown with defaults from theme
  [{'color': []}, {'background': []}],
  [{'font': []}],
  [{'align': []}],
  ['image'],
  // remove formatting button
  ['clean']
]
export default {
  name: 'add',
  data(){
    let checkImg = (rule, value, callback) => {
      if (!this.hasFmt) { //hasFmt设置为true/false
        callback(new Error("请上传新闻封面"));
      } else {
        callback();
      }
    }
    return{
      hasFmt:false,
      //图片url
      dialogImageUrl: '',
      //图片弹出框
      dialogVisible: false,
      //图片配置
      upload: {
        url: this.$action_url,
        headers: {Authorization: window.sessionStorage.getItem('token')},
        data:{
          folder:'article_img'
        },
        name: 'file',
        accept: 'image/*',
        limitCount: 1,
      },
      //新闻类别数组
      articleTypeList:[],
      quillUpdateImg:false,
      article_id:0,
      //自定义新增数组
      addForm:{
        title:'',
        sub_title:'',
        column_id:'1',
        keyword:'',
        description:'',
        source:'',
        author:'',
        img:'',
        content:'',
        hot:false,
        top:false,
        status:true,
      },
      pathList:[],
      //验证
      addRules:{
        title: [
          { required: true, message: '请输入文章名称', trigger: 'blur' },
          { min: 2, max: 125, message: '长度在 2 到 125 个字符', trigger: 'blur' }
        ],
        img: [{ required: true, validator: checkImg }]
      },

      //编辑器配置
      editorOption:{
        placeholder: '请输入内容',
        theme: 'snow',
        modules: {
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          },
          toolbar: {
            container:toolbarOptions,
            handlers: {
              'image': function (value) {
                if (value) {
                  document.querySelector(".quill-avatar-uploader input").click();
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      }
    }
  },
  created () {
    this.article_id = sessionStorage.getItem('article_id') === null ? 0 : sessionStorage.getItem('article_id')
    this.getArticleTypeList();
    if (this.article_id > 0){
      this.editArticle(this.article_id);
    }
    this.hasFmt = true;
  },
  methods:{
     async getArticleTypeList(){
       const {data:res} = await this.$http.get('dashboard/article_type_list')
       if (res.code !== 200) return this.$message.error('获取新闻类别失败');
       this.articleTypeList = res.data.list;
    },
    goBack() {
      this.$router.go(-1);//返回上一层

    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    onSuccess(response, file, fileList){
      if (response.code !== 200) return this.$message.error(response.data.message)
      this.hasFmt = true;
      this.addForm.img = this.$http_url + 'storage/' + response.data.list.path
      this.$refs.image.clearValidate();
    },
    handleRemove(){
      this.hasFmt = false;
      this.addForm.img = ''
      this.$refs.image.validate();
    },
    onExceed(files, fileList){
      if(files.length === 1){
        return this.$message.error('图片超出1张图片的限制,请删除后重新上传')
      }
    },
    // 上传图片前
    beforeUpload(res, file) {
      // 打开上传动画
      this.quillUpdateImg = true
    },
    // 上传图片成功
    uploadSuccess(res,file,fileList) {
      let quill = this.$refs.myQuillEditor.quill
      if (res.code !== 200) return this.$message.error('上传失败');
      // 获取光标所在位置
      let length = quill.getSelection().index;
      // 插入图片  res.info为服务器返回的图片地址
      quill.insertEmbed(length, 'image', this.$http_url + 'storage/' + res.data.list.path)
      // 调整光标到最后
      quill.setSelection(length + 1)

      // loading动画消失
      this.quillUpdateImg = false
    },
    // 上传图片失败
    uploadError(res, file) {
      this.quillUpdateImg = false
      this.$message.error('图片插入失败')
    },
    //保存
    saveArticle(){
      if (this.article_id > 0){
        this.$set(this.addForm, 'id', this.article_id)
      }
      this.$refs.AddRefForm.validate(async valid => {
        if (!valid) return this.$message.error('输入不合法')
        const {data: result} = await this.$http.post('dashboard/article_save', this.addForm)
        if (result.code !== 200) return this.$message.error(result.data.message)
        this.$message.success('新增成功')
        this.$router.push('/dashboard/article_list')
      })
    },
    //读取新闻信息 -- 处理异步请求
    async editArticle(article_id){
      const {data: res} = await this.$http.get('dashboard/article_show/' + article_id)
      if (res.code !== 200) return this.$message.error('获取新闻失败');
      this.addForm = res.data.list;
      this.pathList.push(res.data.list.img_show)
    }
  }
}
</script>

<style lang="scss" scoped>


</style>

